package cn.yusei.teamTribe.dao.team;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import cn.yusei.teamTribe.dao.team.po.TeamRolePO;

@Mapper
public interface TeamRoleDAO {

	final String TEAM_ROLE_USER_TABLE = " r_team_role_user ";
	final String INSERT_FIELDS = " (team_id, role_id, user_id) ";
	
	@Select({
		"<script>",
			"select exists ",
				"(select * from", TEAM_ROLE_USER_TABLE, "where team_id = #{teamId} and user_id = #{userId} and role_id in ",
				"<foreach collection='roleIds' item='roleId' open='(' separator=',' close=')'>",
				"#{roleId} ", 
				"</foreach>",
				" limit 1)",
		"</script>"
		})
	public boolean exists(@Param("teamId") int teamId, @Param("roleIds") int roleIds[], @Param("userId") int userId);
	
	@Select({"select count(*) from", TEAM_ROLE_USER_TABLE, "where team_id = #{teamId} and role_id = #{roleId}"})
	public int cntOf(TeamRolePO teamRolePO);
	
	@Select({"select user_id from", TEAM_ROLE_USER_TABLE, "where team_id = #{teamId} and role_id = #{roleId}"})
	public int[] selectUser(TeamRolePO teamRolePO);
	
	@Select({"select role_id from", TEAM_ROLE_USER_TABLE, "where team_id = #{teamId} and user_id = #{userId}"})
	public Integer selectRole(TeamRolePO teamRolePO);
	
	@Insert({"insert into", TEAM_ROLE_USER_TABLE, INSERT_FIELDS, "values(#{teamId}, #{roleId}, #{userId})"})
	public void insert(TeamRolePO teamRolePO);
	
	@Delete({"delete from", TEAM_ROLE_USER_TABLE, " where team_id = #{teamId} and role_id = #{roleId}"})
	public void deleteRole(TeamRolePO teamRolePO);
	
	@Update({"update", TEAM_ROLE_USER_TABLE, "set user_id = #{userId} where team_id = #{teamId} and role_id = #{roleId}"})
	public void updateUserId(TeamRolePO teamRolePO);
	
	@Update({"update", TEAM_ROLE_USER_TABLE, "set role_id = #{roleId} where team_id = #{teamId} and user_id = #{userId}"})
	public void updateRoleId(TeamRolePO teamRolePO);
}
